package br.com.listener;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

import br.com.model.PerfilManager;

public class FilterListener implements PhaseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void afterPhase(PhaseEvent event) {

	}

	@Override
	public void beforePhase(PhaseEvent event) {
		FacesContext context = event.getFacesContext();
		String currentPage = context.getViewRoot().getViewId();

		boolean isLoginPage = (currentPage.lastIndexOf("index.xhtml") > -1);
		HttpSession session = (HttpSession) context.getExternalContext()
				.getSession(true);
		String currentUser = null;
		PerfilManager pm = new PerfilManager();

		try {
			currentUser = session.getAttribute("perfil").toString();
		} catch (NullPointerException ex) {
			currentUser = null;
		}
		
		if(!currentPage.equals("/public/cadastroPeloUsuario.xhtml")){
			if (!isLoginPage && currentUser == null) {
				NavigationHandler nh = context.getApplication()
						.getNavigationHandler();
				nh.handleNavigation(context, null, "index");
			} else if (currentUser == null) {
				NavigationHandler nh = context.getApplication()
						.getNavigationHandler();
				nh.handleNavigation(context, null, "index");
			} else {
				boolean acesso = pm.verificaPermissao(currentPage, currentUser);
				if (!acesso) {
					NavigationHandler nh = context.getApplication()
							.getNavigationHandler();
					nh.handleNavigation(context, null, "index");
				}
			}
		}

		

	}

	@Override
	public PhaseId getPhaseId() {

		return PhaseId.RENDER_RESPONSE;
	}

}
